package com.ace.scenep.day0116;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 简单HTTP客户端工具类
 */
public class HttpClient {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final int defaultTimeout = 5000; // 默认超时时间5秒
    
    /**
     * 发送GET请求
     */
    public <T> T get(String url, Map<String, String> headers, Class<T> responseType) throws IOException {
        HttpURLConnection conn = createConnection(url, "GET");
        try {
            // 设置请求头
            setHeaders(conn, headers);
            
            // 发送请求并获取响应
            String response = getResponse(conn);
            
            // 转换响应结果
            return parseResponse(response, responseType);
        } finally {
            conn.disconnect();
        }
    }
    
    /**
     * 发送POST请求（JSON格式）
     */
    public <T> T postJson(String url, Object body, Map<String, String> headers, Class<T> responseType) 
            throws IOException {
        HttpURLConnection conn = createConnection(url, "POST");
        try {
            // 设置JSON请求头
            headers = headers != null ? new HashMap<>(headers) : new HashMap<>();
            headers.put("Content-Type", "application/json");
            setHeaders(conn, headers);
            
            // 写入请求体
            String jsonBody = objectMapper.writeValueAsString(body);
            writeBody(conn, jsonBody);
            
            // 获取响应
            String response = getResponse(conn);
            
            // 转换响应结果
            return parseResponse(response, responseType);
        } finally {
            conn.disconnect();
        }
    }
    
    /**
     * 发送POST请求（表单格式）
     */
    public <T> T postForm(String url, Map<String, String> formData, Map<String, String> headers, 
            Class<T> responseType) throws IOException {
        HttpURLConnection conn = createConnection(url, "POST");
        try {
            // 设置表单请求头
            headers = headers != null ? new HashMap<>(headers) : new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            setHeaders(conn, headers);
            
            // 构建表单数据
            StringBuilder formBody = new StringBuilder();
            for (Map.Entry<String, String> entry : formData.entrySet()) {
                if (formBody.length() > 0) {
                    formBody.append('&');
                }
                formBody.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                       .append('=')
                       .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            
            // 写入请求体
            writeBody(conn, formBody.toString());
            
            // 获取响应
            String response = getResponse(conn);
            
            // 转换响应结果
            return parseResponse(response, responseType);
        } finally {
            conn.disconnect();
        }
    }
    
    /**
     * 创建HTTP连接
     */
    private HttpURLConnection createConnection(String url, String method) throws IOException {
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setRequestMethod(method);
        conn.setConnectTimeout(defaultTimeout);
        conn.setReadTimeout(defaultTimeout);
        return conn;
    }
    
    /**
     * 设置请求头
     */
    private void setHeaders(HttpURLConnection conn, Map<String, String> headers) {
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
    }
    
    /**
     * 写入请求体
     */
    private void writeBody(HttpURLConnection conn, String body) throws IOException {
        conn.setDoOutput(true);
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = body.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
    }
    
    /**
     * 获取响应内容
     */
    private String getResponse(HttpURLConnection conn) throws IOException {
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }
    
    /**
     * 解析响应结果
     */
    private <T> T parseResponse(String response, Class<T> responseType) throws IOException {
        if (responseType == String.class) {
            return (T) response;
        }
        return objectMapper.readValue(response, responseType);
    }
} 